package com.cuit.zuke.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cuit.zuke.common.vo.QuarterlyDataVo;
import com.cuit.zuke.common.vo.WeeklyDataVo;
import com.cuit.zuke.order.client.DictFeignClient;
import com.cuit.zuke.order.client.ProductFeignClient;
import com.cuit.zuke.order.client.UserFeignClient;
import com.cuit.zuke.order.mapper.GoodsOrderDetailMapper;
import com.cuit.zuke.order.mapper.GoodsOrderMapper;
import com.cuit.zuke.order.mapper.HotelOrderMapper;
import com.cuit.zuke.order.model.entity.Address;
import com.cuit.zuke.order.model.entity.GoodsOrder;

import com.cuit.zuke.order.model.entity.GoodsOrderDetail;
import com.cuit.zuke.order.model.entity.HotelOrder;
import com.cuit.zuke.order.model.vo.GoodsListVO;
import com.cuit.zuke.order.model.vo.GoodsOrderQueryVO;
import com.cuit.zuke.order.model.vo.GoodsOrderVO;
import com.cuit.zuke.order.service.AddressService;
import com.cuit.zuke.order.service.GoodsOrderService;

import com.cuit.zuke.product.model.entity.Goods;
import com.cuit.zuke.product.model.entity.Stock;
import com.cuit.zuke.product.model.entity.Warehouse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class GoodsOrderServiceImpl extends ServiceImpl<GoodsOrderMapper, GoodsOrder> implements GoodsOrderService {

    @Autowired
    private AddressService addressService;

    @Autowired
    private GoodsOrderDetailMapper goodsOrderDetailMapper;

    @Autowired
    private ProductFeignClient productFeignClient;

    @Autowired
    private DictFeignClient dictFeignClient;

    @Autowired
    private HotelOrderMapper hotelOrderMapper;

    private Map<Stock,Integer> handleOrderResult = new HashMap<>();

    @Autowired
    private UserFeignClient userFeignClient;

    @Autowired
    private GoodsOrderMapper goodsOrderMapper;

    @Override
    @Cacheable(value = "myOrders")
    public Page<GoodsOrderVO> listOrder(Integer current, Integer limit, GoodsOrderQueryVO goodsOrderQueryVO) {
        Page<GoodsOrder> goodsOrderPage = new Page<>(current, limit);
        Page<GoodsOrderVO> goodsOrderVOPage = new Page<>(goodsOrderPage.getCurrent(), goodsOrderPage.getSize());

        // 查询条件
        QueryWrapper<GoodsOrder> queryWrapper = new QueryWrapper<>();
        String orderIdQUE = goodsOrderQueryVO.getOrderId();
        String userIdQUE = goodsOrderQueryVO.getUserId();
        String status = goodsOrderQueryVO.getStatus();
        if(!StringUtils.isEmpty(orderIdQUE)){
            queryWrapper.eq("order_id",orderIdQUE);
        }
        if(!StringUtils.isEmpty(userIdQUE)){
            queryWrapper.eq("user_id",userIdQUE);
        }
        if(!StringUtils.isEmpty(status)){
            if (status.equals("9")){
                // 状态码为9查询订单状态为已处理的：1已发货 2已签收 3已完成 4已关闭
                queryWrapper.in("status",1,2,3,4);
            }else {
                queryWrapper.eq("status",goodsOrderQueryVO.getStatus());
            }

        }

        goodsOrderPage = baseMapper.selectPage(goodsOrderPage, queryWrapper);
        List<GoodsOrder> records = goodsOrderPage.getRecords();
        List<GoodsOrderVO> goodsOrderVOList = new ArrayList<>();
        // GoodsOrder -> GoodsOrderVO
        for (GoodsOrder goodsOrder : records) {
            GoodsOrderVO goodsOrderVO = new GoodsOrderVO();
            // 订单号
            goodsOrderVO.setOrderId(goodsOrder.getOrderId());
            // 用户id
            goodsOrderVO.setUserId(goodsOrder.getUserId());
            // 用户name
            goodsOrderVO.setUserName(userFeignClient.getUserById(goodsOrder.getUserId()).getUserName());
            // 发货地址
            goodsOrderVO.setShipping(goodsOrder.getShippingAddress());
            // 创建时间
            goodsOrderVO.setCreateTime(goodsOrder.getCreateTime());
            //运单号
            goodsOrderVO.setWbNO(goodsOrder.getWbNo());
            // 收货地址
            String receiptId = goodsOrder.getReceiptId();
            Address address = addressService.getById(receiptId);
            String province = dictFeignClient.getNameById(address.getProvinceCode());
            String city = dictFeignClient.getNameById(address.getCityCode());
            String loc = dictFeignClient.getNameById(address.getLocCode());
            goodsOrderVO.setReceipt(province+"-"+city+"-"+loc+"-"+address.getDetailedAddress());
            // 订单商品列表
            String orderId = goodsOrder.getOrderId();
            QueryWrapper<GoodsOrderDetail> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("order_id",orderId);
//            Map<Goods, Integer> goodsMap = new HashMap<>();
            List<GoodsListVO> goodsListVOS = new ArrayList<>();
            List<GoodsOrderDetail> goodsOrderDetails = goodsOrderDetailMapper.selectList(queryWrapper1);
            Double price = 0.0;
            // 遍历中间表，得到订单下所有商品
            // 获取goodsId的list
            if (goodsOrderDetails.size() != 0){
                List<Long> goodsIdList = new ArrayList<>();
                for (GoodsOrderDetail goodsOrderDetail: goodsOrderDetails){
                    goodsIdList.add(goodsOrderDetail.getGoodsId());
                }
                List<Goods> goodsList = productFeignClient.findByIdClis(goodsIdList);
                for (Goods goods : goodsList) {
                    GoodsListVO goodsListVO = new GoodsListVO();
                    goodsListVO.setGoods(goods);
                    for (GoodsOrderDetail orderDetail : goodsOrderDetails) {
                        if (goods.getGoodsId().equals(orderDetail.getGoodsId())){
                            goodsListVO.setNum(orderDetail.getNum());
                            price = goods.getGoodsPrice().doubleValue() * orderDetail.getNum() + price;
                        }
                    }
                    goodsListVOS.add(goodsListVO);
                }
            }
//            for (GoodsOrderDetail goodsOrderDetail : goodsOrderDetails) {
//                Goods goods = productFeignClient.findByIdCli(goodsOrderDetail.getGoodsId());
//                price = goods.getGoodsPrice().doubleValue() * goodsOrderDetail.getNum() + price;
//                // 封装了查询的商品和对应数量的对象
//                GoodsListVO goodsListVO = new GoodsListVO();
//                goodsListVO.setGoods(goods);
//                goodsListVO.setNum(goodsOrderDetail.getNum());
//                goodsListVOS.add(goodsListVO);
////                goodsMap.put(goods,goodsOrderDetail.getNum());
//            }
            goodsOrderVO.setGoodsList(goodsListVOS);
            // 总价
            goodsOrderVO.setTotal(BigDecimal.valueOf(price));
            // 完成时间
            goodsOrderVO.setFinishTime(goodsOrder.getFinishTime());
            // 状态
            goodsOrderVO.setStatus(goodsOrder.getStatus());
            goodsOrderVOList.add(goodsOrderVO);
        }

        goodsOrderVOPage.setRecords(goodsOrderVOList);
        goodsOrderVOPage.setTotal(goodsOrderPage.getTotal());
        return goodsOrderVOPage;
    }

    @Override
    @CacheEvict(value = "myOrders",allEntries = true)
    public boolean deleteById(String order_id) {
        int i = goodsOrderMapper.deleteByOrderId(order_id);
        return i>0;
    }

    @Override
    public boolean handleOrder(GoodsOrderVO goodsOrderVO) {
        // 库存是否充足
        boolean flag = false;
        // 得到商品和数量的map<goodsId，num>
        Map<Long, Integer> goodsMap = new HashMap<>();
        List<GoodsListVO> goodsList = goodsOrderVO.getGoodsList();
        for (GoodsListVO goodsListVO : goodsList) {
            goodsMap.put(goodsListVO.getGoods().getGoodsId(),goodsListVO.getNum());
        }
        // 遍历所有仓库
        List<Warehouse> warehouseList = productFeignClient.listWarehouseCli();
        for (Warehouse warehouse : warehouseList) {
            Integer warehouseId = warehouse.getId();
            List<Stock> stocks = productFeignClient.getByStockWarehouseIdCli(warehouseId);
            flag = handleFH(stocks, goodsMap);

            if (flag){
                flag = true;
                break;
            }
        }
        if (flag){// 库存足够
            Integer i = 0;
            for (Map.Entry<Stock, Integer> entry : handleOrderResult.entrySet()) {
                i = entry.getKey().getWarehouseId();
                Long stockId = entry.getKey().getId();
                Integer num = entry.getValue();
                productFeignClient.reduceStock(stockId,num);
            }
            //更新订单状态
            String orderId = goodsOrderVO.getOrderId();
            QueryWrapper<GoodsOrder> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("order_id",orderId);
            GoodsOrder order = baseMapper.selectOne(queryWrapper);
            byte be = 1;
            order.setStatus(be);
            //设置发货地址
            String warehouseName = productFeignClient.getWarehouseNameById(i);
            order.setShippingAddress(warehouseName);
            baseMapper.update(order,queryWrapper);
            return true;
        }else {//库存不足
            return flag;
        }

    }

    // 生成商品订单
    @Override
    @CacheEvict(value = "myOrders", allEntries = true)
    public GoodsOrder generateOrder(String uid) {

        GoodsOrder goodsOrder = new GoodsOrder();
        goodsOrder.setUserId(uid);  //设置用户id
        // 查询设置该用户下的收货地址id
        QueryWrapper<Address> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("uid",uid);
        Address address = addressService.getOne(queryWrapper);
        goodsOrder.setReceiptId(address.getId()+"");

        // 生成订单号  时间戳+用户id
        SimpleDateFormat sdf =  new SimpleDateFormat("yyyyMMddHHmmss"); //设置格式
        String orderId=sdf.format(new Date())+uid;
        goodsOrder.setOrderId(orderId);

        goodsOrder.setStatus((byte)-1);
        goodsOrder.setCreateTime(new Date());
        goodsOrder.setUpdateTime(new Date());
        goodsOrder.setIsDelete((byte)0);
        goodsOrder.setFinishTime(null);
        goodsOrder.setShippingAddress("");
        baseMapper.insert(goodsOrder);
        return goodsOrder;
    }

    // 生成商品订单和商品的对应表
    @Override
    public GoodsOrderDetail generateOrderDetail(String orderId, Long goodsId) {

        GoodsOrderDetail goodsOrderDetail = new GoodsOrderDetail();
        goodsOrderDetail.setOrderId(orderId);
        goodsOrderDetail.setGoodsId(goodsId);
        goodsOrderDetail.setNum(1);
        int i = goodsOrderDetailMapper.insert(goodsOrderDetail);
        if (i>0){
            return goodsOrderDetail;
        }else {
            return null;
        }

    }

    /**
     * 根据用户id查询该用户的所有订单
     * @param uid
     * @return
     */
    @Override
    @Cacheable(value = "myOrders")
    public List<GoodsOrderVO> findByUid(String uid) {

        // 查询条件
        QueryWrapper<GoodsOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",uid);
        List<GoodsOrder> goodsOrders = baseMapper.selectList(queryWrapper);
        List<GoodsOrderVO> goodsOrderVOList = new ArrayList<>();
        // GoodsOrder -> GoodsOrderVO
        for (GoodsOrder goodsOrder : goodsOrders) {
            GoodsOrderVO goodsOrderVO = new GoodsOrderVO();
            // 订单号
            goodsOrderVO.setOrderId(goodsOrder.getOrderId());
            // 用户id
            goodsOrderVO.setUserId(goodsOrder.getUserId());
            // 用户name
            goodsOrderVO.setUserName(userFeignClient.getUserById(goodsOrder.getUserId()).getUserName());
            // 发货地址
            goodsOrderVO.setShipping(goodsOrder.getShippingAddress());
            // 创建时间
            goodsOrderVO.setCreateTime(goodsOrder.getCreateTime());
            //运单号
            goodsOrderVO.setWbNO(goodsOrder.getWbNo());
            // 收货地址
            String receiptId = goodsOrder.getReceiptId();
            Address address = addressService.getById(receiptId);
            String province = dictFeignClient.getNameById(address.getProvinceCode());
            String city = dictFeignClient.getNameById(address.getCityCode());
            String loc = dictFeignClient.getNameById(address.getLocCode());
            goodsOrderVO.setReceipt(province+"-"+city+"-"+loc+"-"+address.getDetailedAddress());
            // 订单商品列表
            String orderId = goodsOrder.getOrderId();
            QueryWrapper<GoodsOrderDetail> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("order_id",orderId);
            List<GoodsListVO> goodsListVOS = new ArrayList<>();
            List<GoodsOrderDetail> goodsOrderDetails = goodsOrderDetailMapper.selectList(queryWrapper1);
            Double price = 0.0;
            // 遍历中间表，得到订单下所有商品
            // 获取goodsId的list
            List<Long> goodsIdList = new ArrayList<>();
            for (GoodsOrderDetail goodsOrderDetail: goodsOrderDetails){
                goodsIdList.add(goodsOrderDetail.getGoodsId());
            }
            List<Goods> goodsList = productFeignClient.findByIdClis(goodsIdList);
            for (Goods goods : goodsList) {
                GoodsListVO goodsListVO = new GoodsListVO();
                goodsListVO.setGoods(goods);
                for (GoodsOrderDetail orderDetail : goodsOrderDetails) {
                    if (goods.getGoodsId().equals(orderDetail.getGoodsId())){
                        goodsListVO.setNum(orderDetail.getNum());
                        price = goods.getGoodsPrice().doubleValue() * orderDetail.getNum() + price;
                    }
                }
                goodsListVOS.add(goodsListVO);
            }
//            for (GoodsOrderDetail goodsOrderDetail : goodsOrderDetails) {
//                Goods goods = productFeignClient.findByIdCli(goodsOrderDetail.getGoodsId());
//                price = goods.getGoodsPrice().doubleValue() * goodsOrderDetail.getNum() + price;
//                // 封装了查询的商品和对应数量的对象
//                GoodsListVO goodsListVO = new GoodsListVO();
//                goodsListVO.setGoods(goods);
//                goodsListVO.setNum(goodsOrderDetail.getNum());
//                goodsListVOS.add(goodsListVO);
////                goodsMap.put(goods,goodsOrderDetail.getNum());
//            }
            goodsOrderVO.setGoodsList(goodsListVOS);
            // 总价
            goodsOrderVO.setTotal(BigDecimal.valueOf(price));
            // 完成时间
            goodsOrderVO.setFinishTime(goodsOrder.getFinishTime());
            // 状态
            goodsOrderVO.setStatus(goodsOrder.getStatus());
            goodsOrderVOList.add(goodsOrderVO);
        }

        return goodsOrderVOList;
    }

    @Override
    @CacheEvict(value = "myOrders", allEntries = true)
    public GoodsOrderVO paySuccess(String orderId) {

        GoodsOrder goodsOrder = goodsOrderMapper.selectById(orderId);
        if (goodsOrder.getStatus() == -1){
            goodsOrder.setStatus((byte)0);
        }
        goodsOrderMapper.updateById(goodsOrder);
        GoodsOrderVO goodsOrderVO = new GoodsOrderVO();
        // 订单号
        goodsOrderVO.setOrderId(goodsOrder.getOrderId());
        // 用户id
        goodsOrderVO.setUserId(goodsOrder.getUserId());
        // 用户name
        goodsOrderVO.setUserName(userFeignClient.getUserById(goodsOrder.getUserId()).getUserName());
        // 发货地址
        goodsOrderVO.setShipping(goodsOrder.getShippingAddress());
        // 创建时间
        goodsOrderVO.setCreateTime(goodsOrder.getCreateTime());
        //运单号
        goodsOrderVO.setWbNO(goodsOrder.getWbNo());
        // 收货地址
        String receiptId = goodsOrder.getReceiptId();
        Address address = addressService.getById(receiptId);
        String province = dictFeignClient.getNameById(address.getProvinceCode());
        String city = dictFeignClient.getNameById(address.getCityCode());
        String loc = dictFeignClient.getNameById(address.getLocCode());
        goodsOrderVO.setReceipt(province+"-"+city+"-"+loc+"-"+address.getDetailedAddress());
        // 订单商品列表
        String orderId1 = goodsOrder.getOrderId();
        QueryWrapper<GoodsOrderDetail> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("order_id",orderId1);
        List<GoodsListVO> goodsListVOS = new ArrayList<>();
        List<GoodsOrderDetail> goodsOrderDetails = goodsOrderDetailMapper.selectList(queryWrapper1);
        Double price = 0.0;
        // 遍历中间表，得到订单下所有商品
        // 获取goodsId的list
        List<Long> goodsIdList = new ArrayList<>();
        for (GoodsOrderDetail goodsOrderDetail: goodsOrderDetails){
            goodsIdList.add(goodsOrderDetail.getGoodsId());
        }
        List<Goods> goodsList = productFeignClient.findByIdClis(goodsIdList);
        for (Goods goods : goodsList) {
            GoodsListVO goodsListVO = new GoodsListVO();
            goodsListVO.setGoods(goods);
            for (GoodsOrderDetail orderDetail : goodsOrderDetails) {
                if (goods.getGoodsId().equals(orderDetail.getGoodsId())){
                    goodsListVO.setNum(orderDetail.getNum());
                    price = goods.getGoodsPrice().doubleValue() * orderDetail.getNum() + price;
                }
            }
            goodsListVOS.add(goodsListVO);
        }
//        for (GoodsOrderDetail goodsOrderDetail : goodsOrderDetails) {
//            Goods goods = productFeignClient.findByIdCli(goodsOrderDetail.getGoodsId());
//            price = goods.getGoodsPrice().doubleValue() * goodsOrderDetail.getNum() + price;
//            // 封装了查询的商品和对应数量的对象
//            GoodsListVO goodsListVO = new GoodsListVO();
//            goodsListVO.setGoods(goods);
//            goodsListVO.setNum(goodsOrderDetail.getNum());
//            goodsListVOS.add(goodsListVO);
////                goodsMap.put(goods,goodsOrderDetail.getNum());
//        }
        goodsOrderVO.setGoodsList(goodsListVOS);
        // 总价
        goodsOrderVO.setTotal(BigDecimal.valueOf(price));
        // 完成时间
        goodsOrderVO.setFinishTime(goodsOrder.getFinishTime());
        // 状态
        goodsOrderVO.setStatus(goodsOrder.getStatus());

        return goodsOrderVO;
    }

    /**
     * 判断库存list中的商品是否足够
     * @param stocks
     * @param goodsMap
     * @return
     */
    private boolean handleFH(List<Stock> stocks,Map<Long, Integer> goodsMap){
        for (Map.Entry<Long, Integer> entry : goodsMap.entrySet()) {
            // 是否找到该商品
            boolean flag = false;
            Long goodsId = entry.getKey();
            Integer num = entry.getValue();
            for (Stock stock : stocks) {
                if (goodsId == stock.getGoodsId()){
                    if (stock.getNum() >= num){
                        flag = true;
                        handleOrderResult.put(stock,num);
                        break;
                    }
                }
            }
            if (flag){
                continue;
            }else {
                handleOrderResult.clear();
                return false;
            }
        }
        return true;
    }





}
